package com.xmhmyh.generalframework.framework.security;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xmhmyh.generalframework.common.constants.Constants;
import com.xmhmyh.generalframework.framework.redis.IredisService;
import com.xmhmyh.generalframework.framework.uid.UidGenerator;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 于丁
 * @Description: 令牌服务类
 * @DateTime: 2020/7/21 9:45 上午
 * @Params:
 * @Return
 */
@Slf4j
@Component
public class TokenService {

    /**
     * 令牌标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 令牌密钥
     */
    @Value("${token.secret}")
    private String secret;

    /**
     * 令牌有效期
     */
    @Value("${token.expireTime}")
    private Long expireTime;

    @Autowired
    private IredisService redisService;

    @Autowired
    private UidGenerator uidGenerator;
    protected static final long MILLIS_SECOND = 1000;
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    /**
     * @Author: 于丁
     * @Description: 创建令牌
     * @DateTime: 2020/7/21 9:44 上午
     * @Params: loginUser 用户信息
     * @Return
     */
    public String creatToken(LoginUser loginUser) {
        // 生成随机ID
        String token = String.valueOf(uidGenerator.getUID());
        loginUser.setToken(token);
        refreshToken(loginUser);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        redisService.set(Constants.LOGIN_TOKEN_KEY + loginUser.getToken(), loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser 令牌
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 获取LoginUser信息
     *
     * @param httpServletRequest
     * @return
     */
    public LoginUser getLoginUser(HttpServletRequest httpServletRequest) {
        String jwtToken = httpServletRequest.getHeader(header);
        log.info("JWT-TOKEN：" + jwtToken);
        if (StrUtil.isBlank(jwtToken)) {
            return null;
        }
        // 解析jwt
        Claims claims = parseToken(jwtToken);
        String token = (String) claims.get(Constants.LOGIN_USER_KEY);
        if (StrUtil.isBlank(token)) {
            return null;
        }
        LoginUser loginUser = (LoginUser) redisService.get(Constants.LOGIN_TOKEN_KEY + token);
        return loginUser;
    }

    public void removeLoginUser(LoginUser loginUser) {
        redisService.remove(Constants.LOGIN_TOKEN_KEY + loginUser.getToken());
    }
}
